
package com.huizhan.web.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.*;
import io.swagger.annotations.*;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

import com.huizhan.web.view.*;
import com.huizhan.web.dao.*;
import com.huizhan.web.model.*;
import com.huizhan.web.model.Contact;

/**
 * 联系人api
 */
 
@Api(tags = "Contact",description = "联系人")
@RestController
public class ContactController {
    
    @Autowired
    private ContactDao dao;
   
    @Autowired
    private InviteDao iDao;
   
    @Autowired
    private ProjectDao pDao;
   
    @Autowired
    private ContactInviteDao ciDao;
   
    /**
     * 获取联系人集合
     * @return api结果
     */
    @ApiOperation(value = "根据条件获取联系人")
    @RequestMapping(value =  "/api/Contact/{type}/{projectId}/{phone}/",method = {RequestMethod.GET})
    public ApiResult<Contact> Get(@PathVariable Integer type,@PathVariable String projectId,@PathVariable String phone){
         ApiResult<Contact> result=new ApiResult<Contact>();
        try 
        {
            Contact Contact=dao.findByProjectIdAndPhone(projectId,phone);

            result.setData(Contact);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 根据ID获取联系人信息
     * @param id 联系人ID
     * @return api结果
     */
    @ApiOperation(value = "根据ID获取联系人信息")
    @RequestMapping(value =  "/api/Contact/{id}",method = {RequestMethod.GET})
    public ApiResult<Contact> Get(@PathVariable Long id){
        ApiResult<Contact> result=new ApiResult<Contact>();
        try
        {
            Contact model= dao.getOne(id);
            result.setData(model);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 修改联系人信息
     * @param id 联系人ID
     * @param model 联系人信息
     * @return api结果
     */
    @ApiOperation(value = "邀约联系人信息")
    @RequestMapping(value =  "/api/Contact/Invite/{id}",method = {RequestMethod.PUT})
    public ApiResult Invite(@PathVariable Long id,@RequestBody PagePersonal model){

        ApiResult result=new ApiResult();
        try
        {
            Optional<Invite> invate= iDao.findById(id);

            if(!invate.isPresent()){
                result.setHasError(true);
                result.setMessage("参数错误");
            }else{
                Long start=model.getStartDate().getTime()/1000;
                Long end=model.getEndDate().getTime()/1000;
                PageRequest pageable = PageRequest.of(model.getPageIndex(),model.getPageSize(),Direction.DESC,"Contact_Id") ;            
                Page<Contact> page = dao.findByAll(model.getName(),model.getPhone(),model.getProjectId(),model.getCode(),start,end,pageable);
                List<ContactInvite> list=new ArrayList<ContactInvite>();
                String ids="";
                for (Contact contact : page.getContent()) {
                    ContactInvite contactinvite=new ContactInvite();
                    contactinvite.setContactId(contact.getContactId());
                    contactinvite.setContent(invate.get().getContent());
                    contactinvite.setCreateDate(new Date());
                    contactinvite.setProjectId(invate.get().getProjectId());
                    contactinvite.setEmail(contact.getEmail());
                    contactinvite.setInviteId(invate.get().getInviteId());
                    contactinvite.setName(contact.getName());
                    contactinvite.setPhone(contact.getPhone());
                    contactinvite.setTitle(invate.get().getTitle());
                    if(invate.get().getIsEmail()==0&&contact.getPhone()!=null&&contact.getPhone().length()>0){
                        ids+=contact.getPhone()+",";
                        list.add(contactinvite);
                    }else if(invate.get().getIsEmail()==1&&contact.getEmail()!=null&&contact.getEmail().length()>0){
                        ids+=contact.getEmail()+",";
                        list.add(contactinvite);
                    }
                }
                if(list.size()>0){
                    ids=trimBothEndsChars(ids,",");

                    if(invate.get().getIsEmail()==0){
                        Optional<Project> project= pDao.findById(invate.get().getProjectId());
                        String data="{\"account\":\"dh81653\",\"password\":\""+
                        TenpayUtil.MD5("e3YiG73c").toLowerCase()
                        +"\",\"msgid\":\""
                        +(UUID.randomUUID().toString())
                        +"\",\"phones\":"
                        +ids
                        +",\"content\":\""
                        +invate.get().getContent()
                        +"\",\"sign\":\"【"
                        +project.get().getSignName()
                        +"】\",\"subcode\":\"\",\"sendtime\":\"\"}";

                        TenpayHttpClient httpClient = new TenpayHttpClient(); 

                        httpClient.callHttpPost("http://www.dh3t.com/json/sms/Submit", data);
                        httpClient.getResContent();
                    }else{
                        EmailUtil.sendMail(ids, invate.get().getTitle(), invate.get().getContent());
                    }

                    ciDao.saveAll(list);
                }else{
                    result.setHasError(true);
                    result.setMessage("没有数据可以邀约");
                }
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    public static String trimBothEndsChars(String srcStr, String splitter) {    String regex = "^" + splitter + "*|" + splitter + "*$";    return srcStr.replaceAll(regex, "");}
    
    /**
     * 修改联系人信息
     * @param id 联系人ID
     * @param model 联系人信息
     * @return api结果
     */
    @ApiOperation(value = "修改联系人信息")
    @RequestMapping(value =  "/api/Contact/{id}",method = {RequestMethod.PUT})
    public ApiResult<Contact> Edit(@PathVariable Long id,@RequestBody Contact model){
        ApiResult<Contact> result=new ApiResult<Contact>();
        try
        {
            Contact Contact=dao.getOne(id);

            if(Contact==null){
                result.setHasError(true);
                result.setMessage("参数错误");
            }else{
                Contact.setName(model.getName());
                Contact.setCompany(model.getCompany());
                Contact.setAddress(model.getAddress());
                Contact.setArea(model.getArea());
                Contact.setSex(model.getSex());
                Contact.setAvatar(model.getAvatar());
                Contact.setEmail(model.getEmail());
                Contact.setPosition(model.getPosition());
                dao.save(Contact);
                result.setData(Contact);
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 添加人信息
     * @param model 人信息
     * @return api结果
     */
    @ApiOperation(value = "添加联系人信息")
    @RequestMapping(value =  "/api/Contact/{id}",method = {RequestMethod.PATCH})
    public ApiResult<List<Contact>> Add(@PathVariable String id, @RequestBody List<Contact> list){
         ApiResult<List<Contact>> result=new ApiResult<List<Contact>>();
        try
        {
            List<Contact> ls=new ArrayList<Contact>();

            for (Contact model : list) {
                model.setProjectId(id);
                if(model.getPhone()!=""&&dao.findByProjectIdAndPhone(model.getProjectId(),model.getPhone())!=null){
                    result.setMessage(model.getPhone()+"手机号码已存在"+(result.getMessage()==null?"":"\n"+result.getMessage()));
                }else if(model.getEmail()!=""&&dao.findByProjectIdAndEmail(model.getProjectId(),model.getEmail())!=null){
                    result.setMessage(model.getEmail()+"邮箱已存在"+(result.getMessage()==null?"":"\n"+result.getMessage()));
                }else{
                    model.setCreateDate(new Date());
                    ls.add(model);
                }
            }
            
            dao.saveAll(ls);
            result.setData(ls);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 添加联系人信息
     * @param model 联系人信息
     * @return api结果
     */
    @ApiOperation(value = "添加联系人信息")
    @RequestMapping(value =  "/api/Contact/",method = {RequestMethod.POST})
    public ApiResult<Contact> Add(@RequestBody Contact model){
         ApiResult<Contact> result=new ApiResult<Contact>();
        try
        {
             if(model.getProjectId()==""){
                result.setHasError(true);
                result.setMessage("项目ID不能为空");
            }else if(model.getPhone()!=""&&dao.findByProjectIdAndPhone(model.getProjectId(),model.getPhone())!=null){
                result.setHasError(true);
                result.setMessage("手机号码已存在");
            }else if(model.getEmail()!=""&&dao.findByProjectIdAndEmail(model.getProjectId(),model.getEmail())!=null){
                result.setHasError(true);
                result.setMessage("邮箱已存在");
            }else{
                model.setCreateDate(new Date());
                dao.save(model);
                result.setData(model);
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
    
    /**
     * 查询联系人员分页
     * @param model 账号联系人员信息
     * @return api结果
     */
    @ApiOperation(value = "查询观众分页")
    @RequestMapping(value =  "/api/Contact/Search",method = {RequestMethod.POST})
    public ApiResult<List<Contact>> Search(@RequestBody PagePersonal model){
         ApiResult<List<Contact>> result=new ApiResult<List<Contact>>();
         
        try
        {     
            Long start=model.getStartDate().getTime()/1000;
            Long end=model.getEndDate().getTime()/1000;
            PageRequest pageable = PageRequest.of(model.getPageIndex(),model.getPageSize(),Direction.DESC,"Contact_Id") ;            
            Page<Contact> page = dao.findByAll(model.getName(),model.getPhone(),model.getProjectId(),model.getCode(),start,end,pageable);
            result.setData(page.getContent());
            result.setTotal(page.getTotalElements());
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 删除联系人信息
     * @param id 联系人ID
     * @return api结果
     */
    @ApiOperation(value = "删除联系人信息")
    @RequestMapping(value =  "/api/Contact/{id}",method = {RequestMethod.DELETE})
    public ApiResult<Object> Delete(@PathVariable  Long id){
        ApiResult<Object> result=new ApiResult<Object>();
        try 
        {
            dao.deleteById(id);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
}

